package com.lnsf.bookstore.web.book.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lnsf.bookstore.common.annotation.IgnoreAuth;
import com.lnsf.bookstore.common.annotation.LoginUser;
import com.lnsf.bookstore.common.annotation.SysLog;
import com.lnsf.bookstore.common.controller.ApiBaseAction;
import com.lnsf.bookstore.web.address.service.ApiAddressService;
import com.lnsf.bookstore.web.address.vo.ApiAddress;
import com.lnsf.bookstore.web.book.service.ApiBookService;
import com.lnsf.bookstore.web.book.vo.ApiBook;
import com.lnsf.bookstore.web.bookSpecification.service.ApiBookSpecificationService;
import com.lnsf.bookstore.web.bookSpecification.vo.ApiBookSpecification;
import com.lnsf.bookstore.web.cart.service.ApiCartService;
import com.lnsf.bookstore.web.category.controller.ApiCategoryController;
import com.lnsf.bookstore.web.category.service.ApiCategoryService;
import com.lnsf.bookstore.web.category.vo.ApiCategory;
import com.lnsf.bookstore.web.collection.service.ApiCollectService;
import com.lnsf.bookstore.web.coupon.service.ApiCouponService;
import com.lnsf.bookstore.web.coupon.vo.ApiCoupon;
import com.lnsf.bookstore.web.serachHistory.service.ApiSearchHistoryService;
import com.lnsf.bookstore.web.serachHistory.vo.ApiSerachHistory;
import com.lnsf.bookstore.web.user.vo.ApiUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/api/book")
public class ApiBookController extends ApiBaseAction{

    @Autowired
    private ApiBookService apiBookService;
    @Autowired
    private ApiBookSpecificationService apiBookSpecificationService;
    @Autowired
    private ApiCollectService apiCollectService;
    @Autowired
    private ApiCategoryService apiCategoryService;
    @Autowired
    private ApiSearchHistoryService apiSearchHistoryService;
    @Autowired
    private ApiAddressService apiAddressService;
    @Autowired
    private ApiCouponService apiCouponService;
    

    /**
     * 查看所有列表
     */
    @SysLog("前端查看商品详情")
    @ResponseBody
    //@IgnoreAuth
    @RequestMapping("/detail")
    public Object detail(@LoginUser ApiUser apiUser, Integer id) {
        Map<String, Object> resultObj = new HashMap();
        //id = 1;
        JSONObject jsonObject = getJsonRequest();
        id = jsonObject.getInteger("id");
        ApiBook apiBook = apiBookService.queryObject(id);
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("bookId",id);
        //当前用户是否收藏
        Integer userHasCollect = this.isUserCollect(apiUser,id);
        //获得规格列表
        List<Map> specificationList = this.getSpecification(id);

        resultObj.put("bookInfo",apiBook);
        resultObj.put("specificationList", specificationList);
        resultObj.put("userHasCollect", userHasCollect);
        return toResponsSuccess(resultObj);
    }

    //当前用户是否收藏
    private Integer isUserCollect(ApiUser apiUser,Integer bookId){
        Map collectParam = new HashMap();
        //collectParam.put("user_id", getUserId());
        collectParam.put("userId", apiUser.getUserId());
        collectParam.put("bookId", bookId);
        Integer userHasCollect = apiCollectService.queryTotal(collectParam);
        if (userHasCollect > 0) {
            userHasCollect = 1;
        }
        return userHasCollect;
    }

    //获得规格列表
    private List<Map> getSpecification(Integer bookId){
        Map<String,Object> specificationParam = new HashMap<String, Object>();
        specificationParam.put("fields", "bs.*, s.name");
        specificationParam.put("bookId", bookId);
        specificationParam.put("sidx", "s.sort_order");
        specificationParam.put("order", "asc");
        List<ApiBookSpecification> bookSpecificationList = apiBookSpecificationService.quertList(specificationParam);
        //存储规格的列表，map中有规格id,名称，还有属于该规格的列表
        List<Map> specificationList = new ArrayList();
        //按规格名称分组
        for (int i = 0; i < bookSpecificationList.size(); i++) {
            ApiBookSpecification specItem = bookSpecificationList.get(i);

            //临时List,存放到Map中的，代表分组规格中的列表
            List<ApiBookSpecification> tempList = null;
            for (int j = 0; j < specificationList.size(); j++) {
                if (specificationList.get(j).get("specificationId").equals(specItem.getSpecificationId())) {
                    tempList = (List<ApiBookSpecification>) specificationList.get(j).get("valueList");
                    break;
                }
            }
            if (tempList == null) {
                Map temp = new HashMap();
                temp.put("specificationId", specItem.getSpecificationId());
                temp.put("name", specItem.getName());
                tempList = new ArrayList();
                tempList.add(specItem);
                temp.put("valueList", tempList);
                specificationList.add(temp);
            } else {
                for (int j = 0; j < specificationList.size(); j++) {
                    if (specificationList.get(j).get("specificationId").equals(specItem.getSpecificationId())) {
                        tempList = (List<ApiBookSpecification>) specificationList.get(j).get("valueList");
                        tempList.add(specItem);//添加
                        break;
                    }
                }
            }
        }
        return specificationList;
    }


    /**
     * 　获取分类下的商品
     */
    @IgnoreAuth
    @ResponseBody
    @RequestMapping("category")
    public Object category(@LoginUser ApiUser loginUser, Integer id) {
        Map<String,Object> objectMap = new HashMap<String, Object>();
        ApiCategory apiCategory = apiCategoryService.queryObject(id);
        Map map = new HashMap();
        map.put("parentCode",apiCategory.getParentCode());

        List<ApiCategory> brotherCategoryList = apiCategoryService.queryList(map).getList();
        objectMap.put("currentCategory", apiCategory);
        objectMap.put("brotherCategoryList", brotherCategoryList);
        return toResponsSuccess(objectMap);
    }

    /**
     * 　　获取商品列表
     */
    @IgnoreAuth
    @ResponseBody
    @RequestMapping("list")
    public Object list(@LoginUser ApiUser loginUser, Integer categoryId,
                        String keyword, Integer isNew, Integer isHot,
                       @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size,
                       String sort, String order) {
        Map<String,Object> resultMap = new HashMap<String, Object>();

        Map params = new HashMap();
        params.put("isOnSale", 1);
        params.put("keyword", keyword);
        params.put("isNew", isNew);
        params.put("isHot", isHot);
        params.put("page", page);
        params.put("limit", size);
        params.put("order", sort);
        params.put("sidx", order);

        //排序问题
        if (null != sort && sort.equals("price")) {
            params.put("sidx", "unit_price");
            params.put("order", order);
        } else if (null != sort && sort.equals("isNew")) {
            params.put("sidx", "is_new");
            params.put("order", order);
        } else if(null != sort && sort.equals("saleNum")){
            params.put("sidx", "sale_num");
            params.put("order", order);
        }else{
            params.put("sidx", "id");
            params.put("order", "desc");
        }
        //添加到搜索历史
        if (StringUtils.isNotBlank(keyword)) {
            ApiSerachHistory searchHistoryVo = new ApiSerachHistory();
            searchHistoryVo.setAddTime(new Date());
            searchHistoryVo.setKeyword(keyword);
            searchHistoryVo.setUserId(getUserId());
            searchHistoryVo.setSource("");
            apiSearchHistoryService.save(searchHistoryVo);
        }

        //筛选的分类
        List<ApiCategory> filterCategory = new ArrayList();
        ApiCategory rootCategory = new ApiCategory();
        rootCategory.setId(0);
        rootCategory.setName("全部");
        rootCategory.setChecked(false);
        filterCategory.add(rootCategory);

        //分类ids
        if (null != categoryId && categoryId > 0) {
            ApiCategory apiCategory = apiCategoryService.queryObject(categoryId);
            List<Integer> categoryIds = new ArrayList();
            Map categoryParam = new HashMap();
            categoryParam.put("parentCode", apiCategory.getCode());
            categoryParam.put("fields", "id");
            PageInfo<ApiCategory> childIds = apiCategoryService.queryList(categoryParam);
            for (ApiCategory categoryEntity : childIds.getList()) {
                categoryIds.add(categoryEntity.getId());
            }
            categoryIds.add(categoryId);
            params.put("categoryIds", categoryIds);
        }
        //查询列表数据
        params.put("fields", "id, name, list_pic_url, unit_price, description ");
        List<ApiBook> booksList = apiBookService.queryList(params);
        resultMap.put("bookList",booksList);
        resultMap.put("filterCategory",filterCategory);
        return toResponsSuccess(resultMap);
    }

    /**
     * 　　新品首发
     */
    @IgnoreAuth
    @ResponseBody
    @RequestMapping("new")
    public Object newAction(@LoginUser ApiUser loginUser) {
        Map<String, Object> resultObj = new HashMap();
        Map map = new HashMap();
        map.put("page", 1);
        map.put("limit", 10);
        map.put("order", "desc");
        map.put("sidx", "create_time");
        map.put("isNew",1);
        List<ApiBook> list = apiBookService.queryList(map);
        resultObj.put("newBookList",list);
        return toResponsSuccess(resultObj);
    }

    /**
     * 　　人气推荐
     */
    @IgnoreAuth
    @ResponseBody
    @RequestMapping("hot")
    public Object hot(@LoginUser ApiUser loginUser) {
        Map<String, Object> resultObj = new HashMap();
        Map map = new HashMap();
        map.put("page", 1);
        map.put("limit", 10);
        map.put("order", "desc");
        map.put("sidx", "create_time");
        map.put("isHot",1);
        List<ApiBook> list = apiBookService.queryList(map);
        resultObj.put("hotBookList",list);
        return toResponsSuccess(resultObj);
    }

    /**
     * 　　商品详情页的大家都在看的商品
     */
    @IgnoreAuth
    @ResponseBody
    @RequestMapping("related")
    public Object related(@LoginUser ApiUser loginUser, Integer id) {
        Map<String, Object> resultObj = new HashMap();

        return toResponsSuccess(resultObj);
    }


    /**
     * 　　在售的商品总数
     */
    @IgnoreAuth
    @ResponseBody
    @RequestMapping("count")
    public Object count(@LoginUser ApiUser loginUser) {
        Map<String, Object> resultObj = new HashMap();
        return toResponsSuccess(resultObj);
    }

    @ResponseBody
    @RequestMapping("checkout")
    public Object checkout(@LoginUser ApiUser loginUser) {
        Map<String, Object> resultObj = new HashMap();
        Map map = new HashMap();
        JSONObject jsonObject = getJsonRequest();
        String jsonString = jsonObject.getString("bookInfo");
        Map mapTypes = JSON.parseObject(jsonString);
        Integer bookId = (Integer) mapTypes.get("bookId");
        Integer couponId = (Integer) mapTypes.get("couponId");
        int num = (int) mapTypes.get("num");

        JSONArray jsonArray = (JSONArray) mapTypes.get("specificationInfo");
        List<ApiBookSpecification> apiBookSpecificationList = jsonArray.toJavaList(ApiBookSpecification.class);

        ApiBook apiBook = apiBookService.queryObject(bookId);
        apiBook.setApiBookSpecificationList(apiBookSpecificationList);

        //地址
        map.put("userId",loginUser.getUserId());
        List<ApiAddress> apiAddressList = apiAddressService.queryByUid(map);
        if(apiAddressList.size()!=0){
            resultObj.put("address",apiAddressList.get(0));
        }else {
            resultObj.put("address","");
        }

        //获取可用的优惠券信息
        Map usercouponMap = new HashMap();
        usercouponMap.put("userId", loginUser.getUserId());
        List<ApiCoupon> couponList = apiCouponService.queryUserCouponList(usercouponMap);
        ApiCoupon checkedCoupon = null;
        BigDecimal couponPrice = new BigDecimal(0.00);  //使用优惠券减免的金额
        if (null != couponList && couponList.size() > 0) {
            for (ApiCoupon couponVo : couponList) {
                if (null != couponId && couponId.equals(couponVo.getId())) {
                    couponPrice = couponVo.getParPrice();
                    checkedCoupon = couponVo;
                }
            }
        }
        //计算订单的费用
        //根据收货地址计算运费
        BigDecimal freightPrice = new BigDecimal(10.00);
        //商品总价
        BigDecimal booksTotalPrice = apiBook.getUnitPrice().multiply(new BigDecimal(num));
        //订单的总价
        BigDecimal orderTotalPrice = booksTotalPrice.add(freightPrice);
        //实际金额
        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);  //减去其它支付的金额后，要实际支付的金额
        resultObj.put("num",num);
        resultObj.put("booksTotalPrice", booksTotalPrice);//商品总金额
        resultObj.put("orderTotalPrice", orderTotalPrice);//订单总金额
        resultObj.put("actualPrice", actualPrice);//实际总金额
        resultObj.put("freightPrice", freightPrice);    //运费金额
        resultObj.put("couponList", couponList);//优惠券列表
        resultObj.put("bookInfo", apiBook);//
        resultObj.put("couponPrice", couponPrice);//选中的优惠券金额
        return toResponsSuccess(resultObj);
    }

}
